<?php

namespace App\Repository\UpThree;

use App\Api\CatchOrder\DouYinNew;
use App\Jobs\OrderSubmit;
use App\Repository\BaseRepository;
use App\Repository\CatchConf\DouYinCatchRepository;
use App\Repository\CatchConf\DouYinRepository;
use Illuminate\Support\Facades\DB;
use Monolog\Formatter\LineFormatter;
use Monolog\Handler\RotatingFileHandler;
use Monolog\Logger;

/**
 * 抖音订单处理
 */
class DouYinOrderRepostition extends BaseRepository
{

    private $goodsModel;
    private $productModel;
    private $orderProductModel;
    private $channelModel;
    private $orderModel;
    private $userMoneyLog;
    private $log;

    public function __construct()
    {

        $this->log = new Logger('catchNewOrder');
        $this->log->pushHandler(
            (new RotatingFileHandler(storage_path('/logs/catchNewOrder.log'), 14, Logger::DEBUG, true, 0777))->setFormatter(new LineFormatter(null, null, true, true))
        );
        parent::__construct();
    }
    /**
     * 抖音订单处理
     */


    /**
     * 抖音类型处理
     * shop_id 店铺号
     * pid  订单号
     */
    public function getDouYinOrders($data = array())
    {
        // 取订单的详情
        // 根据获取到的订单信息 处理订单的状态
        $this->log->info('抖音抓取时的数据:' . json_encode($data));
        // 根据推送过来的信息 获取订单详情 需要对接
        if (empty($data['shop_id'])) {
            return $this->returnMsg(103, '抖音信息为空');
        }
        $douyinRModel = new DouYinRepository();
        $whereDouYin = [
            'app_shop_id' => $data['shop_id'],
            'nums' => 1
        ];
        $resDouYin = $douyinRModel->getOne($whereDouYin);

        if (empty($resDouYin)) {
            return $this->returnMsg(104, '未查询抖音配置');
        }
        // 查询抖音的数据
        $douyinModel = new DouYinNew($resDouYin->app_shop_id, $resDouYin->app_key, $resDouYin->app_secret);

        $resDouYinDetails = $douyinModel->orderDetails($data);
        if (empty($resDouYinDetails['data'][0])) {
            return $this->returnMsg(200, '未查询到订单信息');
        }
        if ($resDouYinDetails['code']) {

        }
        $disUserId = '';
        $disUserName = '';
        $resDouYinDetail = $resDouYinDetails['data'][0];
        $orderData = [
            'source' => 1,  // 数据来源
            'goods_code' => $resDouYinDetail['product'],
            'province' => $resDouYinDetail['province'],
            'city' => $resDouYinDetail['city'],
            'area' => $resDouYinDetail['area'],
            'shop_id' => $resDouYin->shop_id,
            'dist_orderno' => $resDouYinDetail['order_num'],
            'dist_id' => $resDouYin->id,
            'dist_name' => !empty($resDouYin->remark) ? $resDouYin->remark : '',
            'author_id' => $resDouYinDetail['author_id'],
            'author_name' => $resDouYinDetail['author_name'],
            'remark' => $resDouYinDetail['c_biz_desc'],
            'dou_status' => $resDouYinDetail['dou_status'],
            'douyin_id' => !empty($disUserId) ? $disUserId : 0, //抖音信息
            'douyin_name' => !empty($disUserName) ? $disUserName : '', //抖音店铺名称
            'money' => !empty($resDouYinDetail['money']) ? $resDouYinDetail['money'] : 0,
        ];
        if (!empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
            $orderData['name'] = $resDouYinDetail['user_name'];
            $orderData['identity'] = $resDouYinDetail['card_num'];
            $orderData['contact'] = $resDouYinDetail['user_phone'];
            $orderData['address'] = (!empty($resDouYinDetail['street']) ? $resDouYinDetail['street'] : '') . $resDouYinDetail['addr'];

        }
        // 存入到订单表中
        $res = [];
        $orderData['status'] = 0;
        $models = new DouYinCatchRepository();
        $isTrueOrder = $models->getOne(['dist_orderno' => $orderData['dist_orderno']]);
        if ($isTrueOrder) {
//             判断用户名和手机号 身份证号是否为空
            if (!empty($isTrueOrder->user_name) && !empty($isTrueOrder->user_phone) && !empty($isTrueOrder->user_phone)) {
                return $this->returnMsg(101, '用户已提交');
//                return ['status' => 101, 'msg' => '用户已提交'];
            }
        }
        // if (!empty($resDouYinDetails['code']) && $resDouYinDetails['code'] == 200) {
        //     $model = new MainOrderRepostition();
        //     $orderDatas = $orderData;
        //     if (!empty($orderDatas['douyin_id'])) {
        //         $orderDatas['shop_id'] = $orderDatas['douyin_id'];
        //         $orderDatas['source'] = 6;
        //     }
        //     $res = $model->orderSubmit($orderDatas);
        //     $orderData['status'] = 0;
        // }
        $orderData['three_msg'] = !empty($res['msg']) ? $res['msg'] : (!empty($resDouYinDetail['seller_words']) ? $resDouYinDetail['seller_words'] : '订单已关闭');
        // if (!empty($res['code']) && $res['code'] != 200) {
        //     $orderData['status'] = 60;
        // }
        $orderData['package_name'] = !empty($resDouYinDetail['package_name']) ? $resDouYinDetail['package_name'] : '';
        $orderData['created_at'] = !empty($resDouYinDetail['created_at']) ? $resDouYinDetail['created_at'] : '';
        $orderData['douyin_status_name'] = !empty($resDouYinDetail['douyin_status_name']) ? $resDouYinDetail['douyin_status_name'] : '';
        $returnId = '';
        if ($isTrueOrder) {
            $returnId = $orderData['dist_orderno'];
            $isTrue = $models->edit(['dist_orderno' => $orderData['dist_orderno']], $orderData);
        } else {
            $insertData = $models->add($orderData);
        }
        //  有个消息通知
        $postData = [
            'url' => $resDouYin->return_url,
            'order' => $orderData
        ];
        dispatch(new OrderSubmit($postData, 'postCatchOrder', 5))->onQueue('TaskOrderSubmitDispose');
        // 直接返回查询到的信息
        return $resDouYinDetails;
    }

    //
    //  提交到新系统 订单
    public function postCatchOrder($postData)
    {

        if (empty($postData['url'])) {
            return $this->returnMsg(100, '推送链接未配置');
        }
        $url = $postData['url'];
        $data = $postData['order'];
        if (!is_array($data)) {
            $res = DB::table('douyin_catch')->where(['dist_orderno' => $data])->first();
            $data = json_decode(json_encode($res), true);
        }
        return $this->getNewSystem($url, $data);
    }
    /**
     * 参数:
     * goods_code,name,identity,contact,province,city,area,address,dist_orderno,dist_id,
     * dist_name,author_id,author_name,package_name,douyin_id,douyin_name,sell_id,sell_name
     */
    // 包含订单信息的修改
    public function getNewSystem($url, $data = array())
    {
        //
        return $this->sendPost($url, $data);
    }

    // 推送地址信息   post 提交订单
    function sendPost($url, $post_data)
    {
        $opt_data = json_encode($post_data);

        $header = array();
        $header[] = 'Accept:application/json';
        $header[] = 'Content-Type:application/json;charset=utf-8';
        // var_dump($url);
        // var_dump($header);
        // var_dump($opt_data);
        $curl = curl_init();  //初始化
        curl_setopt($curl, CURLOPT_URL, $url);  //设置url
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $opt_data);
        // curl_setopt($curl,CURLOPT_POST,1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        //从证书中检查SSL加密算法是否存在
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        //post请求
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_POST, 1);

        $result = curl_exec($curl);
        // var_dump($result);
        if ($result === false) {
            echo curl_errno($curl);
            exit();
        }
        curl_close($curl);
        return $result;
    }
}
